package com.qf.listener;

import com.qf.SearchApplication;
import com.qf.config.DelayedConfig;
import com.qf.config.ElasticsearchConfig;
import com.qf.constant.RabbitMQConstants;
import com.qf.model.StandardReport;
import com.qf.model.StandardSubmit;
import com.qf.util.JsonUtils;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;

import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author YDW
 * projectName:project2202_4
 * time:2022/6/23 16:49
 * description:
 */
@Component
@Slf4j
public class SendLogListener {

    @Autowired
    RestHighLevelClient highLevelClient;

    @RabbitListener(queues = RabbitMQConstants.TOPIC_SMS_SEND_LOG)
    public void sendLog(StandardSubmit submit, Channel channel, Message message) throws IOException {
        String json = JsonUtils.object2Json(submit);
        IndexRequest request=new IndexRequest("sms_submit_log");
        request.id(submit.getSequenceId()).source(json, XContentType.JSON);
        IndexResponse index = highLevelClient.index(request, RequestOptions.DEFAULT);
        log.info("[搜索模块 -- 日志保存] 保存成功！！ submit={}",submit);
        //手动ack（手动确认消息）
        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }



    @Autowired
    RabbitTemplate template;

    @RabbitListener(queues = RabbitMQConstants.TOPIC_UPDATE_SMS_REPORT)
    public void reportUpdate(StandardReport report, Channel channel, Message message){

        //参数4： 消息的后处理对象
        template.convertAndSend(DelayedConfig.DELAYED_EXCHANGE, "esKey", report, new MessagePostProcessor() {
            @Override
            public Message postProcessMessage(Message message) throws AmqpException {
                //设置延时时间
                message.getMessageProperties().setDelay(10000);
                return message;
            }
        });
        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    @RabbitListener(queues = DelayedConfig.DELAYED_QUEUE)
    public void consumDelay(StandardReport report,Channel channel,Message message) throws IOException {
        //准备一个submit对象
        StandardSubmit submit = new StandardSubmit();
        submit.setSequenceId(report.getSequenceId());
        submit.setDestMobile(report.getMobile());
        submit.setReportState(report.getState());
        submit.setErrorCode(report.getErrorCode());
        submit.setSrcSequenceId(report.getSrcID());
        submit.setClientID((int) report.getClientID());
        submit.setMsgid(report.getMsgId());
        //2. 转换成json格式
        String json = JsonUtils.object2Json(submit);

        //2. 创建修改请求对象, 第一个参数: 索引名字, 第二个参数:修改的文档id
        UpdateRequest request = new UpdateRequest();
        //设置修改后的内容, 第二个参数: 文档数据类型
        request.index("sms_submit_log").id(report.getSequenceId()).doc(json, XContentType.JSON);

        //3. 通过client对象执行
        highLevelClient.update(request, RequestOptions.DEFAULT);

        log.info("[搜索模块 -- 更新es] 更新成功！！");
        //手动ack（手动确认消息）
        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
